package com.boodaba.todocarts.app;

import java.util.HashMap;
import java.util.Map;

import com.boodaba.todocarts.domain.ILabelRepository;
import com.boodaba.todocarts.domain.Label;
import com.boodaba.todocarts.domain.Todo;
import com.google.inject.Inject;

public class TodoSettingsPresenter extends BasePresenter<ITodoSettingsActivity> {

	private ILabelRepository mLabelRepository;
	private Label mTargetLabel;
	
	@Inject
	public TodoSettingsPresenter(ILabelRepository labelRepository) {
		mLabelRepository = labelRepository;
	}
	
	public void initializeWith(ITodoSettingsActivity activity) {
		super.initializeWith(activity);
		
		mTargetLabel = mLabelRepository.getLabelByTitle(
				getActivity().getTargetLabelTitle());
		getActivity().setWorkingTitle(mTargetLabel.getTitle());
		Map<String, Boolean> todoTitles = new HashMap<String, Boolean>();
		for (Todo todo : mTargetLabel.getAllTodos()) {
			todoTitles.put(todo.getTitle(), todo.isCompleted());
		}
		getActivity().setWorkingList(todoTitles);
	}

	public void submitInput() {
		String selectedTitle = getActivity().getSelected();
		String input = getActivity().getInputString().trim();
		
		boolean emptyIn = (input.length() == 0);
		boolean existIn = (mTargetLabel.getTodoByTitle(input) != null);
		
		boolean isNew = (selectedTitle == null
						&& !emptyIn
						&& !existIn);
		
		boolean isUpdt = (selectedTitle != null
						&& !emptyIn
						&& !existIn);
		
		boolean isDel = (selectedTitle != null
						&& emptyIn);
		
		boolean needSave = (isNew || isUpdt || isDel);
		
		if (isNew) {
			mTargetLabel.inviteTodo(input);
			getActivity().addToWorkingList(input);
		}
		
		if (isUpdt) {
			mTargetLabel.replaceTodo(selectedTitle, input);
			getActivity().replaceInWorkingList(input);
		}
		
		if (isDel) {
			mTargetLabel.removeTodo(selectedTitle);
			getActivity().removeFromWorkingList();
		}
		
		if (needSave) {
			mLabelRepository.save(mTargetLabel);
		}
	}

	public void checkItem() {
		final String selectedTitle = getActivity().getSelected();
		boolean isCompleted = mTargetLabel.getTodoByTitle(selectedTitle).isCompleted();
		
		if (isCompleted) {
			mTargetLabel.inviteTodo(selectedTitle);
			getActivity().chargeInWorkingList();
		}
		
		if (!isCompleted) {
			mTargetLabel.completeTodo(selectedTitle);
			getActivity().dischargeInWorkingList();
		}
		
		mLabelRepository.save(mTargetLabel);
	}
}
